use datasource_connector::modeling_connector::SimpleMetaConnector;
use datasource_connector::restful::get_class;
use model_graph_types::modeling::system_meta_database;
use tauri::{command, AppHandle, Runtime, State, Window};

use crate::handlers::ContextState;
use crate::handlers::Result;

use model_graph_types::{
    database::DatabaseType,
    modeling::{Class, MetaConnector},
};

#[command]
pub async fn meta_find_class<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    class_identifier: String,
) -> Result<Class> {
    //获取到数据源
    let context = state.context.clone();
    //查询
    let instance = get_class(context, &class_identifier).await?;

    Ok(instance)
}

#[command]
pub async fn meta_domain_classes<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    domain_identifier: String,
) -> Result<Vec<Class>> {
    //获取到数据源
    let context = state.context.clone();
    //查询
    let instance =
        datasource_connector::restful::meta_domain_classes(context, &domain_identifier).await?;

    Ok(instance)
}

#[command]
pub async fn meta_generate_sql<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    domain_identifier: String,
    database_type: DatabaseType,
) -> Result<Vec<String>> {
    //
    let connector = SimpleMetaConnector::new_with_meta_datasource(&Some(system_meta_database()?))?;

    //查询
    let instance = connector
        .generate_sql(&domain_identifier, database_type)
        .await?;

    Ok(instance)
}
